/**
 * 
 * @authors youzhao.zhou@pandauu.com
 * @date    2016-09-22 13:31:58
 * @version $Id$
 * 
 * 渲染消息
 * 添加单条消息
 * 
 * 
 */

;(function(root,factory){

  if(typeof exports === 'object' && typeof module === 'object'){
    
    factory(exports);

  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['exports'], factory);
  } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
    // CommonJS
    factory(exports);
  } else {
    // Browser globals
    if (!root._s) {
      root._s = {};
    }
    factory(root);
  }
})(typeof window !== 'undefined' ? window : this ,function(exports, undefined){
  'use strict';

  function moduleInit($, log, conf, _, IScroll, options){

    var urlConf = conf._conf;       //存储配置信息

    /*
      调试开关
    */
    log._logToggle(true);

    getMsg(_);
    getOrders(_);
    getLabel(_);

    online();

    function getMsg(_){

      
      /*
        获取历史消息
      */
      $.ajax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.msgList,
        type: 'GET',
        dataType: 'json',
        data: {
          thread_id : options.thread_id
        }
      })
      .done(function(data) {
        if (data.code === 0) {

          for(var k in data.data){
            if (data.data[k].type === '1') {

              data.data[k].msg = setUrl(data.data[k].msg);
            }else{
              data.data[k].msg = urlConf.root + data.data[k].msg;
              data.data[k].thumb = data.data[k].msg.replace('uploads/kf/','uploads/kf/');
            }
          }
          renderMsg(_, data.data);

          imgDefer();
        }else if(data.code === 100){
          window.location.href = urlConf.root + urlConf.static + 'login.php';
        }
          
      })
      .fail(function() {
        log._log("error");
      })
      .always(function() {
        log._log("complete");
      });
      
      /*
        服务器推送消息
      */
      var sse = new EventSource(urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.sseUser + '?thread_id=' + options.thread_id);

      sse.onmessage = function(data){
        log._log(data);
        var data = JSON.parse(data.data);
        if (typeof data !== 'undefined' && data.code === 0) {
          $('.has-msg').removeClass('s-hide');
          setTimeout(function(){
            $('.has-msg').addClass('s-hide');
          },2000);
          for(var k in data.data){
            if (data.data[k].type === '1') {

              data.data[k].msg = setUrl(data.data[k].msg);
            }else{
              data.data[k].msg = urlConf.root + data.data[k].msg;
              data.data[k].thumb = data.data[k].msg.replace('uploads/kf/','uploads/kf/thumbnail/');
              //data.data[k].thumb = data.data[k].msg.replace('uploads/kf/','uploads/kf/');
            }
          }
          renderOneMsg(_, data.data);
          imgDefer();
        }
        log._log(data);
        
      };
    }
    
    /*
      获取标签备注
    */
    function getLabel(_){
      $.ajax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.tagsRemarks,
        type: 'GET',
        dataType: 'json',
        data: {
          thread_id : options.thread_id
        }
      })
      .done(function(data) {

        if (data.code === 0) {

          renderLabel(_, data.tags);
          
          $('.jsLabelLists').width(($('.jsLabelLists>li').width()+parseFloat($('.jsLabelLists>li').css('margin-left'))+parseFloat($('.jsLabelLists>li').css('border-width'))+parseFloat($('.jsLabelLists>li').css('margin-right')))*$('.jsLabelLists>li').length/parseFloat($('html').css('font-size')) + 'rem');

          startLabelScroll();

        }
          
      })
      .fail(function() {
        log._log("error");
      })
      .always(function() {
        log._log("complete");
      });
    }
      

    /*
      获取订单
    */
    function getOrders(_){
      $.ajax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.thread,
        type: 'GET',
        dataType: 'json',
        data: {
          thread_id : options.thread_id
        }
      })
      .done(function(data) {

        if (data.code === 0) {

          /*
            设置导航头部
          */
          $('.middle').html(data.data.username);

          
          if (data.data.products.length>0) {
            renderOrder(_, data.data.products);
            startScroll();
          }
            
        }else{
          $('#order').css({
              height: '0'
            });
        }
          
      })
      .fail(function() {
        $('#order').css({
          height: '0'
        });
        log._log("error");
      })
      .always(function() {
        log._log("complete");
      });
    }
    /*
      订单列表滑动事件
    */
    function startScroll () {
      new IScroll('.order-container', {
        zoom: true,
        scrollX: true,
        scrollY: false,
        mouseWheel: true,
        tap: true,
        click: true,
        snap: true,
        snapSpeed: 400,
        keyBindings: true,
      });
    }

    /*
      标签滑动事件
    
    */
    function startLabelScroll () {
      new IScroll('.label-container', {
        zoom: true,
        scrollX: true,
        scrollY: false,
        mouseWheel: true,
        tap: true,
        click: true,
        snapSpeed: 400,
      });
    }
    /*
      文字信息URL处理
    */
    function setUrl(str){
      /*
        验证是否带有请求头正则
      */
      var reg = /(http:\/\/|https:\/\/)/g;
      /*
        提取URL正则
      */
      var reg1 = /((http:\/\/|https:\/\/)(((\w|=|\?|\/|&|-)+)(\.)((\.|\w|=|\?|\/|&|-)+)))/g;
      var reg2 = /((\w|=|\?|\/|&|-)+)(\.)((\.|\w|=|\?|\/|&|-)+)/g;
      if (reg2.test(str)) {
        if (!reg.test(str)) {
          str = str.replace(str.match(reg2)[0], '<a class="url-style" href="' + "http://" + str.match(reg2)[0] + '">' + str.match(reg2)[0] + '</a>');
        }else{
          str = str.replace(reg1, '<a class="url-style" href="$1">$1</a>');
        }
      }

      log._log(str);
      return str;
    }

    /*
      渲染消息
    
    */
    function renderMsg(_, data){
      var msgItemTpl = $('#msgItemTpl');

      $('.chat-container').html(_.template(msgItemTpl.html())({list: data}));

      //$('body')[0].scrollTop = $('.chat-container').height() + parseFloat($('.chat-container').css('padding-top')) + parseFloat($('.chat-container').css('padding-bottom')) - $(window).height();

      $('body')[0].scrollTop = $('.jsService').height()-$(window).height();
    }
    /*
      单条渲染消息
    
    */
    function renderOneMsg(_, data){
      var msgItemTpl = $('#msgItemTpl');

      $('.chat-container').append(_.template(msgItemTpl.html())({list: data}));

      setTimeout(function(){
        //$('body')[0].scrollTop = $('.chat-container').height() + parseFloat($('.chat-container').css('padding-top')) + parseFloat($('.chat-container').css('padding-bottom')) - $(window).height();

        //$('body')[0].scrollTop = $('.jsService').height()-$(window).height();
      },0);
      
    }
    /*
      渲染订单列表
    */
    function renderOrder(_, data){
      var orderItemTpl = $('#orderItemTpl');

      $('#orderMain').html(_.template(orderItemTpl.html())({list: data}));

    }
    /*
      渲染标签列表
    */
    function renderLabel(_, data){
      var tpl = $('#labelTpl');

      $('.jsLabelLists').html(_.template(tpl.html())({list: data}));

    }

    /*
      图片延时加载
    */

    function imgDefer(){
      var isDeferr = $('[data-deferr]').data('deferr');
      var doms = $('[data-deferr]');

      doms.each(function(index, el) {
        var self = this;
        var imgUrl = $(self).data('url');

        var img = new Image();

          img.onload = function(){
            $(self).parent().removeClass('img-start');
            $(self).attr({
              src : imgUrl
            });

            
            if (img.height < 600) {
              $(self).parent().css({
                height : 'auto'
              });
            }
          };

          img.src = imgUrl;
      });

    }

    
    function online(){
      $.ajax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.online,
        type: 'GET',
        dataType: 'json'
      })
      .done(function() {
        setTimeout(function(){
          online();
        },2000);
        log._log("success");
      })
      .fail(function() {
        log._log("error");
      })
      .always(function() {
        log._log("complete");
      });
    };

    window.addEventListener('unload',function(){
      log = null;
      $.ajax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.offline,
        type: 'GET',
        dataType: 'json'
      })
      .done(function() {
        log._log("success");
      })
      .fail(function() {
        log._log("error");
      })
      .always(function() {
        log._log("complete");
      });

      $.ajax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.logoutThread,
        type: 'GET',
        dataType: 'json',
        data: {
          thread_id: options.thread_id
        }
      })
      .done(function() {
        log._log("success");
      })
      .fail(function() {
        log._log("error");
      })
      .always(function() {
        log._log("complete");
      });
      
    },false);

  }

  exports.msgItem = moduleInit;

});